import { useEffect } from "react";
import { useSelector } from "react-redux";
import { matchRoutes, useLocation, useNavigate } from "react-router-dom";
import routers from "./index";
import type { RootState } from "../store";


const AuthRoute = ({ children, auth }: any) => {
    const location = useLocation()
    const navigate = useNavigate()
    const token = useSelector((state: RootState) => {
        return state.userInfo.token
    });

    const mathchs = matchRoutes(routers, location);
    const isExist = mathchs?.some((item) => item.pathname === location.pathname);

    useEffect(() => {
        if (!token && auth) {
            navigate("/login");
        }
        if (token && isExist) {
            if (location.pathname === "/login") {
                navigate("/");
            } else {
                navigate(location.pathname);
            }
        }
    }, [token, location.pathname]);
    return children;
};
export default AuthRoute;
